<?php
declare (strict_types=1);

namespace app\listener;

use app\common\job\ConsultingRushExp;
use app\common\job\LawyerResponseStatistics;
use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\common\model\ConsultingServer;
use app\index\service\ConsultingLawyerMatchService;
use app\index\traits\MessageSendTrait;
use ShidianUtil\Delay\DelayTask;
use ShidianUtil\Utils\TimeUtil;
use think\facade\Config;
use think\facade\Queue;

class ConsultingQuestionBind
{
    use MessageSendTrait;

    /**
     * 咨询和问题绑定 事件监听处理
     */
    public function handle(Consulting $consulting)
    {
        if ($consulting->isAsked != 1) {
            return;
        }

        // 绑定问题后

        $now = time();

        // 先触发咨询变动事件
        event('ConsultingUpdated', $consulting);

        if (is_id($consulting->lawyerId)) {
            // 指定了律师

            // 律师匹配过期时长
            $expTime = Config::get('consulting.designate_time');

            // 律师工作台开始倒计时
            $consulting->rushExpTime = $now + $expTime;
            $consulting->save();

            // 设置抢单过期任务
            $job_data = ['id' => $consulting->id];
            Queue::later($expTime + 3, ConsultingRushExp::class, $job_data);

            // 延迟统计律师咨询数
            $job_data = ['id' => $consulting->lawyerId];
            Queue::later($expTime + 10, LawyerResponseStatistics::class, $job_data);

            if ($consulting->consultingType == 0) {
                // 免费咨询
                // 废弃

                // 推荐的服务
                $recommendServer = null;

                // 咨询的初始服务
                $freeServer = ConsultingServer::where('id', $consulting->consultingServerId)->find();
                if ($freeServer) {
                    $recommendServer = ConsultingServer::where('id', $freeServer->recommendServerId)->find();
                }

                // 发消息给用户：律师已收到，正在分析案情
                if ($recommendServer) {
                    $btnStr = '立即支付';

                    $content = [
                        'text' => '我已收到您的信息，正在为您分析案情，请点击下方的“' . $btnStr . '”后，我们开始' . humanized_time_length($recommendServer->chatFreelyDuration * 3600) . '不限次畅聊',
                    ];
                    $this->getMessageSendService()->sendMemberMessage($consulting, 1, $consulting->lawyerId, ConsultingMessage::TEXT, $content);

                    // 推荐服务卡片消息  延时3秒
                    $this->getDelayTask()
                        ->push(function () use ($recommendServer, $consulting, $btnStr) {
                            sleep(3);
                            $content = [
                                'id' => $recommendServer->id,
                                'btnStr' => $btnStr,
                                // cancel_card 101请求取消接口 102前端拦截弹窗
                                'cancel_card' => '102',
                            ];
                            $this->getMessageSendService()->sendSystemMessage($consulting, 0, ConsultingMessage::SERVER, $content);

                        });

                } else {
                    $content = [
                        'text' => '我已收到您的信息，正在为您分析案情，请耐心等待',
                    ];
                    $this->getMessageSendService()->sendMemberMessage($consulting, 1, $consulting->lawyerId, ConsultingMessage::TEXT, $content);
                }

            } else {
                // 付费咨询

                // 发消息给用户：律师已收到，正在分析案情
                $content0 = [
                    'text' => '我已收到您的信息，正在为您分析案情，请耐心等待'
                ];
                $this->getMessageSendService()->sendMemberMessage($consulting, 1, $consulting->lawyerId, ConsultingMessage::TEXT, $content0);
            }

        } else {
            // 没有指定律师

            // 随机匹配律师
            if ($consulting->matchType == Consulting::MATCH_TYPE_RANDOM) {
                // 不可达-废弃（从落地页和3步曲来的是 SVIP -> 抢单 或者 推送给案如云）

                if ($consulting->consultingType == 0) {
                    // 免费咨询

                    // 咨询的初始服务
                    $freeServer = ConsultingServer::where('id', $consulting->consultingServerId)->find();

                    // 每日赠送免费咨询最大次数
                    $maxTimes = 0;
                    if ($freeServer) {
                        $maxTimes = $freeServer->maxTimes;
                    }

                    // 用户创建的咨询今天赠送了多少次
                    $count = Consulting::where('memberId', $consulting->memberId)
                        ->where('freeNum', '>', 0)
                        ->where('created', '>=', TimeUtil::stamp(TimeUtil::DAY, $now))
                        ->where('created', '<=', TimeUtil::stamp(TimeUtil::DAY, $now, false))
                        ->count();

                    if ($count < $maxTimes) {
                        // 还有免费咨询次数

                        // 发悬赏卡片消息
                        $content0 = [];
                        $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::REWARD, $content0);

                    } else {
                        // 没有免费咨询次数了

                        // 百分比卡片
                        $content1 = [
                            'text' => '正在为您优先匹配金牌律师，请稍等....'
                        ];
                        $this->getMessageSendService()->sendRobotMessage($consulting, null, 0, ConsultingMessage::TEXT, $content1);

                        // XX个律师愿意接单卡片
                        $this->sendLawyersAndRecommendServerMessage($consulting, $freeServer->recommendServerId);
                    }

                } else {
                    // 付费咨询

                    // 百分比卡片
                    $content = [
                        'text' => '正在为您优先匹配金牌律师，请稍等....'
                    ];
                    $this->getMessageSendService()->sendRobotMessage($consulting, null, 0, ConsultingMessage::TEXT, $content);

                    // 立即随机分配一个律师
                    $this->getConsultingLawyerMatchService()->matchRand($consulting);

                }

            }

        }

    }

    private function getConsultingLawyerMatchService(): ConsultingLawyerMatchService
    {
        return app(ConsultingLawyerMatchService::class);
    }

    private function getDelayTask(): DelayTask
    {
        return app(DelayTask::class);
    }
}
